package com.example.usbfileutils

import android.util.Log
import java.util.concurrent.CountDownLatch
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class FileCopyExecutors {

    private val executors: ExecutorService = Executors.newSingleThreadExecutor()
    private val copyTaskQueue: MutableList<FileCopyTask> = ArrayList()
    private lateinit var countDownNumber: CountDownLatch

    companion object {
        val TAG = "FileCopyExecutors"
    }

    fun addTask(copyTask: FileCopyTask) {
        copyTaskQueue.add(copyTask)
    }

    fun start(listener: Listener) {

        if (copyTaskQueue.size == 0) {
            Log.d(TAG, "copyTaskQueue is empty")
            return
        }

        countDownNumber = CountDownLatch(copyTaskQueue.size)

        Log.d(TAG, "start copyfile Task, all task size is ${copyTaskQueue.size}")

        Thread {
            Log.d(TAG, "start await --")
            countDownNumber.await()
            Log.d(TAG, "All task complete--")
            listener.onComplete()

        }.start()

        copyTaskQueue.forEach {
            it.countDownLatch = countDownNumber

            executors.submit(it)
        }

        copyTaskQueue.clear()
        listener.onStart()

    }

    fun stop() {
        Log.d(TAG, "stop the executor")

        executors.shutdown()
    }

    interface Listener {
        fun onStart()
        fun onComplete()
    }

}